package com.lq.dao;

import com.alibaba.fastjson.JSONObject;
import com.lq.common.Constants;
import com.lq.utils.jdbc.Jdbc;
import com.lq.utils.jdbc.LqJdbcFactory;
import com.lq.utils.jdbc.LqPiLiang;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

public class MultiThreadHost extends Thread {

    public static Logger logHost = Logger.getLogger("host");
    private String terraceType;
    private List<ListOrderedMap> companyList;
    private List<Object> subList;
    private CountDownLatch countDownLatch;

    public void setTerraceType(String terraceType) {
        this.terraceType = terraceType;
    }

    public void setCompanyList(List<ListOrderedMap> companyList) {
        this.companyList = companyList;
    }

    public void setSubList(List<Object> subList) {
        this.subList = subList;
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try {
            int result = 0;
            List<Object[]> objectList = new ArrayList<>();
            //source      主机同步来源（1.客户端上传  2.平台创建  3.MQTT服务上传)
            //source_type 主机同步类型（0.客户端主机  1.客户端分机  2.平台主机  3.MQTT主机）
            String hostSql = """
                    insert ignore into manage_host (company_code, area_code, host_num, host_name, host_sn, host_type, source, source_type, is_bind, iccid)  values ( ?,?,?,?,?,?,?,?,?,?)
                        on  duplicate key update  company_code = ?, area_code = ?, host_num = ?, host_name = ?, host_sn =?, host_type =?, source = ?, source_type =?, is_bind = ?, iccid = ?
                    """;
            logHost.info("Thread " + Thread.currentThread().getName() + " is processing  dataSize" + subList.size());

            //将企业编号和库区编号放到Map中进行下面判断处理
            Map<String, String> companyAreaMap = new HashMap<>();
            if(Constants.TERRACE_TYPE.equals(terraceType) && companyList != null){
                companyList.stream().forEach(company -> {
                    String companyCode = company.get("company_code") != null ? company.get("company_code").toString() : "";
                    String areaCode = company.get("area_code") != null ? company.get("area_code").toString() : "";
                    String key = companyCode + "_" + areaCode;
                    companyAreaMap.put(key, companyCode);
                });
            }
            for (int i = 0; i < subList.size(); i++) {
                JSONObject hostJson = JSONObject.parseObject(subList.get(i).toString());
                String companyCode = hostJson.getString("company_code");
                String areaCode = hostJson.getString("area_code");
                //私有化平台的话才进行判断
                if(Constants.TERRACE_TYPE.equals(terraceType)){
                    String key = companyCode + "_" + areaCode;
                    if(!companyAreaMap.containsKey(key)){
                        continue; //如果不存在则跳过，不添加到Object中
                    }
                }
                String hostSn = hostJson.getString("host_sn");
                String hostNum = hostJson.getString("host_num");
                String hostName = hostJson.getString("host_name");
                String hostType = hostJson.getString("host_type");
                String hasBindDevice = hostJson.getString("has_bind_device");
                String iccid = hostJson.getString("iccid");
                String iccidCode = StringUtils.isNotBlank(iccid) && !"null".equals(iccid) ? iccid : null;

                Object[] obj = new Object[]{
                        companyCode,
                        areaCode,
                        hostNum,
                        hostName,
                        hostSn,
                        hostType,
                        "3",
                        "3",
                        hasBindDevice,
                        iccidCode,

                        companyCode,
                        areaCode,
                        hostNum,
                        hostName,
                        hostSn,
                        hostType,
                        "3",
                        "3",
                        hasBindDevice,
                        iccidCode
                };
                objectList.add(obj);
            }
            int[] piliangResult = Jdbc.piliang(hostSql, new LqPiLiang() {
                public void piliang(LqJdbcFactory jdbc) {
                    objectList.forEach(l -> {
                        jdbc.executeS(l);
                    });
                }
            });
            if (piliangResult != null) {
                result = 1;
            }
            logHost.info("==========================================主机数据：" + (result > 0 ? "成功" : "失败") + " ======================================");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (countDownLatch != null) {
                countDownLatch.countDown();
            }
        }
    }
}
